var tiRequest;
var tiRequest1;
var status;

/**
*	Functions to scann file system for music
*/
function getMusic() {
	var messageDiv = document.getElementById("searchMessage");
	var form = document.getElementById('musicSearchForm');
	var path = form.path.value;
	form.path.disabled = true;
	form.submit.disabled = true;
	
	messageDiv.innerHTML = "Searching "+path;
	var url = 'albumManagement.htm';
	var parameters = 'path='+path;
	tiRequest = getXMLRequestObj();
	tiRequest.onreadystatechange = musicProcess;
	tiRequest.open("POST", url, true);
	tiRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	tiRequest.setRequestHeader("Content-length", parameters.length);
	tiRequest.setRequestHeader("Connection", "close");
	tiRequest.send(parameters);

	try {
		tiRequest.send(null); //safari/firefox
	} catch (e) {
		//Just ignore.
	}
	
	status = setInterval("getMusicSearchStatus();", 5000);
}

function musicProcess() {
	if(tiRequest.readyState == 4) {
		if(tiRequest.status == 200) {
			var response = tiRequest.responseText;
			processMusic(response);
			tiRequest = null;
		}
	}
}

function processMusic(response) {
	var searchStatus = document.getElementById("searchStatus");
	searchStatus.innerHTML = response;
	clearInterval(status);
	
	var form = document.getElementById('musicSearchForm');
	form.path.disabled = false;
	form.submit.disabled = false;
	
	var messageDiv = document.getElementById("searchMessage");
	messageDiv.innerHTML = "Search Finished.";
}

/**
* 		Check the status of the search.
*/

function getMusicSearchStatus() {
	var url = 'musicSearchStatus.htm';
	tiRequest1 = getXMLRequestObj();
	tiRequest1.onreadystatechange = musicSearchStatusProcess;
	tiRequest1.open("POST", url, true);
	tiRequest1.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	tiRequest1.setRequestHeader("Connection", "close");
	
	try {
		tiRequest1.send(null); //safari/firefox
	} catch (e) {
		//Just ignore.
	}
}

function musicSearchStatusProcess() {
	if(tiRequest1.readyState == 4) {
		if(tiRequest1.status == 200) {
			var response = tiRequest1.responseText;
			processMusicSearchStatus(response);
			tiRequest1 = null;
		}
	}
}

function processMusicSearchStatus(response) {
	document.getElementById("searchStatus").innerHTML = response;
}

/**
* 	Try to re-init the searc if th user leaves the search page and returns or refreshes the page.
*/
function restoreSearch(searchPath) {
	var form = document.getElementById('musicSearchForm');
		form.path.value = searchPath;
		form.path.disabled = true;
		form.submit.disabled = true;
		
		var messageDiv = document.getElementById("searchMessage");
		messageDiv.innerHTML = "Searching  "+searchPath+"...";
		
		status = setInterval("getMusicSearchStatus();", 5000);
}